# 头条极速版
import random

from common.mytRpc import MytRpc
import time
from utils import *


class TouTiaoJiSu:
    def __init__(self, android, devinfo):
        print("devinfo",android, devinfo)
        self.devinfo = devinfo
        self.into_user = False
        # 头条极速
        self.scheme_js = f"snssdk35://microapp?app_id={devinfo['appid']}&bdp_log=%7B%22launch_from%22%3A%22ad%22%2C%22location%22%3A%22%22%7D&scene=0&start_page=pages%2Fquestion%2Fad%3F&version=v2&version_type=current&bdpsum=880db2b"
        # 今日头条
        self.scheme_tt = f"snssdk141://microapp?app_id={devinfo['appid']}&bdp_log=%7B%22launch_from%22%3A%22ad%22%2C%22location%22%3A%22%22%7D&scene=0&start_page=pages%2Fquestion%2Fad%3F&version=v2&version_type=current&bdpsum=880db2b"
        # 关闭红包弹窗
        self.close_money_window = False
        # 关闭隐私协议弹窗
        self.close_privacy_window = False
        self.android = android
        ip = android['ip']
        port = int(android['RPC'].split(":")[1])
        self.mytapi = MytRpc()
        sdk_ver = self.mytapi.get_sdk_version()
        # success 完成 ad 进入广告 first 首次进入小程序
        self.page_state = ''
        self.count = 0
        self.tt_count = 0
        self.js_count = 0
        if devinfo['app_type'] == 2:
            self.js_count = 3
        # 这里错误
        win_log(f"SDK 版本号:  {sdk_ver} IP {ip} prot {port}  ", '', android['Name'])
        app_msg = f"小程序名 {devinfo['app_name']}({devinfo['app_id']}) 真机ID {devinfo['devinfo_id']} 任务ID:{devinfo['auto_id']}"
        win_log(app_msg, '', android['Name'])
        if self.mytapi.init(ip, port, 10) == True:
            if self.check_connect_state() == True:
                win_log(f"{ip}当前连接状态正常", '', android['Name'])
            else:
                win_log(f"{ip}当前连接断开", 'error', android['Name'])

    def set_android_status(self, status):
        DkGlobal().android_docker.android_list[self.android['ip']]['status'] = status
        DkGlobal().android_docker.update_table()

    def time_sleep(self, _time):
        while True:
            if _time <= 0:
                break
            time.sleep(1)
            _time -= 1
            DkGlobal().android_docker.android_list[self.android['ip']]['time'] = _time
            DkGlobal().android_docker.update_table()

    # 极速开始
    def jsStart(self):
        # 进入个人中心
        self.into_user_wait()
        # 打开小程序
        self.open_min_app(1)
        while True:
            if self.js_count >= 5:
                break
            # 打开小程序广告
            res = self.click_min_app_ad()
            if res == True:
                # 等待广告加载
                res = self.wait_ad_play()
                if res == True:
                    self.set_android_status(f'极速看完{self.js_count}次')
                    ServerApi().set_devinfo_used(self.devinfo['app_id'], self.devinfo['devinfo_id'], self.devinfo['auto_id'], 1)
                    self.time_sleep(random.randint(10, 20))
                else:
                    win_log("wait_ad_play", 'error', self.android['Name'])
            self.js_count += 1

    # 头条开始
    def toutiaoStart(self):
        self.open_min_app(2)
        while True:
            if self.tt_count >= 5:
                break
            # 打开小程序广告
            res = self.click_min_app_ad()
            if res == True:
                # 等待广告加载
                res = self.wait_ad_play()
                if res == True:
                    self.set_android_status(f'头条看完{self.tt_count}次')
                    ServerApi().set_devinfo_used(self.devinfo['app_id'], self.devinfo['devinfo_id'], self.devinfo['auto_id'], 2)
                    self.time_sleep(random.randint(10, 20))
                else:
                    win_log("wait_ad_play",'error',self.android['Name'])
            self.tt_count += 1


    # 自动化点击广告
    def start(self):
        # 打开小程序APP
        try:
            self.jsStart()
            self.set_android_status('极速全部完成，等待1-10秒')
            self.time_sleep(random.randint(10, 20))
            self.toutiaoStart()
            self.set_android_status('头条完成')
        except Exception as e:
            print("打开APP start：",e)

    def wait_ad_play(self, count=0):
        if count > 5:
            print("等待广告播放太久了")
            return False
        res = self.check_page("秒后可领奖励", 20)
        if res == True:
            self.set_android_status('看完广告')
            self.time_sleep(random.randint(20, 30))
            self.set_android_status('准备返回')

        res = self.check_page("返回", 10)
        if res == True:
            self.mytapi.clickDesc("返回")
            self.time_sleep(3)

        res = self.check_page("领取成功", 10)
        if res == True:
            self.set_android_status('领取成功')
            self.time_sleep(3)
            self.mytapi.clickText("领取成功")
            self.time_sleep(3)
        res = self.check_page('查看答案', 10)
        if res == True:
            return True
        else:
            count += 1
            self.wait_ad_play(count)

    def check_page(self, text, timeout):
        _time = 0
        while True:
            if _time >= timeout:
                print(f"执行{text}检测超时")
                return False
            if text in self.dumpNodeXml():
                return True
            else:
                _time += 1

    # 点击小程序广告
    def click_min_app_ad(self, count=0):
        if count > 5:
            return False
        start_time = time.time()
        timeout = 20  # 设置超时时间为5秒
        while True:
            if "查看答案" in self.dumpNodeXml() and "点击退出小程序" in self.dumpNodeXml():
                # 如果找到了"测试字符"，则继续在此处执行你需要的操作
                self.time_sleep(2)
                self.mytapi.clickText("查看答案")
                self.time_sleep(3)
                if "确定" in self.dumpNodeXml() and "提示" in self.dumpNodeXml():
                    self.set_android_status("点击弹窗确认")
                    self.time_sleep(2)
                    self.mytapi.clickText("确定")
                    _count = 0
                    while True:
                        if _count >= 5:
                            self.click_min_app_ad(count + 1)
                        if "秒后可领奖励" in self.dumpNodeXml():
                            self.time_sleep(3)
                            self.count = 0
                            return True
                        else:
                            _count += 1
                else:
                    # 这里卡死了
                    self.click_all_text()
                    self.set_android_status("再次点击广告")
                    self.time_sleep(3)
                    self.click_min_app_ad(count + 1)
                break
            elif time.time() - start_time > timeout:
                return False
            else:
                time.sleep(1)  # 每0.1秒检查一次

    # 打开小程序广告弹窗
    def open_min_app(self, app_type):
        self.open_app(app_type)
        while True:
            win_log(f"当前次数：{self.count}", '', self.android['Name'])
            if self.count >= 2:
                win_log("超出最大次数", 'error', self.android['Name'])
                return False
            xml = self.dumpNodeXml()
            # 打开小程序
            win_log(f"准备处理并进入小程序{self.android['Name']}", '', self.android['Name'])
            self.time_sleep(5)
            if self.close_privacy_window == False or self.close_money_window == False:
                if "个人信息保护指引" in xml:
                    win_log(f"处理隐私协议{self.android['Name']}", '', self.android['Name'])
                    self.privacy_click()
                    self.open_min_app(app_type)
                    return False
                elif "你收到一个现金红包" in xml:
                    self.time_sleep(5)
                    self.money_click()
                    self.open_min_app(app_type)
                    return False
                elif "未登录" in xml and "首页" in xml:
                    print('当前应用进入首页了')
                    # 关闭应用重新进入
                    self.mytapi.stopApp("com.ss.android.article.lite")
                    # 首页
                    self.time_sleep(2)
                    self.open_min_app(app_type)

            while "小程序加载失败" in xml:
                self.time_sleep(2)
                win_log("小程序加载失败", 'error')
                self.open_min_app(app_type)
            while "首次使用小程序" in self.dumpNodeXml():
                self.time_sleep(3)
                print("首次进入小程序，准备中...")
            # 小程序转圈等待页面
            self.set_android_status('等待APP')
            while "microapp_m_loading_icon" in self.dumpNodeXml():
                self.time_sleep(3)
            self.set_android_status('加载页面')
            while "正在加载页面" in self.dumpNodeXml():
                self.time_sleep(3)
            # 进入的瞬间可能白屏
            self.time_sleep(3)
            self.set_android_status('小程序页')
            if "点击退出小程序" in self.dumpNodeXml():
                self.count = 0
                return True
            self.count += 1

    def privacy_click(self):
        res = self.mytapi.clickId("com.ss.android.article.lite:id/vs")
        if res == True:
            print("关闭隐私协议弹窗")
            self.close_privacy_window = True
        return res

    # 现金红包弹窗处理
    def money_click(self):
        res = self.mytapi.clickId("com.ss.android.article.lite:id/rg")
        if res == True:
            print("关闭现金红包弹窗")
            self.close_money_window = True
        return res

    # 测试连接性
    def check_connect_state(self):
        return self.mytapi.check_connect_state()

    def open_app(self, app_type):
        print("打开应用。。。。。。。")
        if app_type == 1:
            scheme = self.scheme_js
        else:
            scheme = self.scheme_tt
        cmd = f"am start -a android.intent.action.VIEW -d \"{scheme}\""
        res = self.mytapi.exec_cmd(cmd)
        if res == True:
            print("打开应用成功")
        return res

    def into_user_wait(self):
        self.mytapi.openApp("com.ss.android.article.lite")
        self.set_android_status('进入头条极速')
        # 比如我这里，想判断res中的文字是否存在"测试字符"，但是如果说5秒内没有存在就执行其他操作要怎么写？
        start_time = time.time()
        timeout = 10  # 设置超时时间为5秒
        while True:
            xml_output = self.mytapi.dumpNodeXml(1)

            if "未登录" in xml_output and "跳过广告" not in xml_output:
                # 如果找到了"测试字符"，则继续在此处执行你需要的操作
                self.time_sleep(3)
                self.mytapi.clickText('未登录')
                count = 0
                while True:
                    if count >= 10:
                        break
                    if "我的网盘" in self.dumpNodeXml():
                        self.set_android_status('进入个人中心')
                        self.into_user = True
                        break
                    else:
                        self.mytapi.clickText('未登录')
                        self.time_sleep(1)
                        count += 1
                # 休息1分钟以上
                self.time_sleep(random.randint(60, 80))
                break
            elif time.time() - start_time > timeout:
                self.into_user = True
                break
            else:
                time.sleep(1)  # 每0.1秒检查一次

    def get_running_apps(self):
        print("查询所有运行中的应用...")
        cmd = "adb shell ps | grep u0_a"  # 这个命令会列出所有用户空间的应用程序
        output = self.mytapi.exec_cmd(cmd)
        print("output", output)
        if output:
            running_apps = []
            for line in output.split('\n'):
                if line.strip():  # 忽略空行
                    parts = line.split()
                    pid = parts[1]
                    appName = parts[8]
                    running_apps.append((pid, appName))

            print("运行中的应用列表:")
            for pid, appName in running_apps:
                print(f"PID: {pid}, 应用名称: {appName}")
            return running_apps
        else:
            print("没有找到运行中的应用.")
            return None

    # 当前不知道啥页面的时候都点一下
    def click_all_text(self):
        texts = ['查看答案', "确定", '领取成功', '未登录']
        descs = ['返回']
        for text in texts:
            self.mytapi.clickText(text)
        for desc in descs:
            self.mytapi.clickDesc(desc)

    # 打印Xml信息
    def dumpNodeXml(self):
        return self.mytapi.dumpNodeXml(True)


class Test():
    def __init__(self):
        self.mytapi = MytRpc()
        sdk_ver = self.mytapi.get_sdk_version()
        print(f"sdk版本号{sdk_ver}")
        # 这里错误
        if self.mytapi.init("192.168.9.104", 9083, 10) == True:
            if self.mytapi.check_connect_state() == True:
                print("链接正常")
            else:
                print("链接失败")


if __name__ == '__main__':
    test = Test()
    # test.mytapi.openApp("com.ss.android.article.lite")
    res = test.mytapi.dumpNodeXml(1)
    print(res)

    test.mytapi.clickText('领取成功')
    # # 比如我这里，想判断res中的文字是否存在"测试字符"，但是如果说5秒内没有存在就执行其他操作要怎么写？
    # while "测试字符" in test.mytapi.dumpNodeXml(1):
    #     pass
    # start_time = time.time()
    # timeout = 10  # 设置超时时间为5秒
    # while True:
    #     xml_output = test.mytapi.dumpNodeXml(1)
    #     print("检查登录")
    #     if "未登录" in xml_output and "跳过广告" not in xml_output:
    #         # 如果找到了"测试字符"，则继续在此处执行你需要的操作
    #         print("点击按钮")
    #         time.sleep(3)
    #         res = test.mytapi.clickText('未登录')
    #         print("res", res)
    #         print(xml_output)
    #         break
    #     elif time.time() - start_time > timeout:
    #         # 如果超过5秒还没有找到"测试字符"，则退出循环
    #         print("超时，未找到'测试字符'")
    #         break
    #     else:
    #         # 等待一小段时间后再次尝试检查
    #         time.sleep(0.1)  # 每0.1秒检查一次
    # time.sleep(5)
    #
    # scheme = f"snssdk35://microapp?app_id=tt3c434afea37582eb01&bdp_log=%7B%22launch_from%22%3A%22ad%22%2C%22location%22%3A%22%22%7D&scene=0&start_page=pages%2Fquestion%2Fad%3F&version=v2&version_type=current&bdpsum=880db2b"
    # cmd = f"am start -a android.intent.action.VIEW -d \"{scheme}\""
    # res = test.mytapi.exec_cmd(cmd)
    # if res == True:
    #     print("打开应用成功")
    # print(res)
    # time.sleep(3)
    # test.mytapi.clickText('未登录')
    # time.sleep(5)
    # res = test.mytapi.dumpNodeXml(1)
    # print(res)
    pass
    # "IP 192.168.9.104 prot 9083  "
    # "小程序名 休闲评测(5) 真机ID 326 任务ID:3 应用类型:1"
    # self = TouTiaoJiSu({"RPC":"192.168.9.104:9083","ip":"192.168.9.104","Name":"TEST"},{})

# if "确定" in self.dumpNodeXml() and "提示" in self.dumpNodeXml():
#     print("有提示")
#     res = self.mytapi.clickText("确定")
#     print(res)

# cmd = "  ps | grep u0_a"  # 这个命令会列出所有用户空间的应用程序
# output = tt.mytapi.exec_cmd(cmd)
# print("output",output)
# tt.get_running_apps()
# xml = tt.dumpNodeXml()
# privacy = "个人信息保护指引"
# money = "你收到一个现金红包"
# if privacy in xml:
#     # 处理隐私协议
#     print("处理隐私协议")
#     tt.privacy_click()
#
# if money in xml:
#     # 处理现金
#     print("处理红包弹窗")
#     tt.money_click()
